package com.sxs.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sxs.entity.EduSubject;
import com.sxs.entity.excel.SubjectData;
import com.sxs.exceptionhandler.CustomizeExceptionHandler;
import com.sxs.exceptionhandler.GlobalExceptionHandler;
import com.sxs.service.EduSubjectService;

/**
 * @Create by Intellij IDEA
 * @Author: songXuSheng
 * @Date: 2021/9/27 17:04
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
    private EduSubjectService eduSubjectService;

    public SubjectExcelListener() {
    }

    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null){
            throw new CustomizeExceptionHandler(20001,"文件为空");
        }
        EduSubject eduOneSubject = this.existOneSubject(eduSubjectService, subjectData.getOneSubjectName());
        if (eduOneSubject == null){
            eduOneSubject =new EduSubject();
            eduOneSubject.setParentId("0");
            eduOneSubject.setTitle(subjectData.getOneSubjectName());
            eduSubjectService.save(eduOneSubject);
        }
        String pid=eduOneSubject.getId();
        EduSubject eduTwoSubject = this.existTwoSubject(eduSubjectService,subjectData.getTwoSubjectName(),pid);
        if (eduTwoSubject == null){
            eduTwoSubject =new EduSubject();
            eduTwoSubject.setParentId(pid);
            eduTwoSubject.setTitle(subjectData.getTwoSubjectName());
            eduSubjectService.save(eduTwoSubject);
        }
    };
    //判断一级分类不能重复添加
    private EduSubject existOneSubject(EduSubjectService eduSubjectService,String name){
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject oneSubject = eduSubjectService.getOne(wrapper);
        return oneSubject;
    }
    //判断二级分类不能重复添加
    private EduSubject existTwoSubject(EduSubjectService eduSubjectService,String name,String pid){
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject twoSubject = eduSubjectService.getOne(wrapper);
        return twoSubject;
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
